package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Manages the connection to the DB. 
 *
 */
public class DBManager {

	private static final String USER = "root";
	private static final String PASSWORD = "9a6b3df996";
	private static final String HOST = "localhost";
	private static final int PORT = 3306;

	private static final int DEFAULT_RETRY_COUNT = 2;
	private static Connection conn = null;


	private DBManager () {	
	}



	private static void connect () throws SQLException {

		int retryCount = DEFAULT_RETRY_COUNT;
		conn = null;

		do {
			try {
				System.out.println("DB_MANAGER: Trying to connect to remote host... ("+retryCount+")");
				conn = DriverManager.getConnection("jdbc:mysql://"+HOST+":"+PORT+"?user="+USER+"&password="+PASSWORD);
				
				retryCount=0;
				System.out.println("DB_MANAGER: Connected to DB!");
				return;
			} catch (SQLException e2) {
				retryCount--;
			}
		} while (retryCount != 0);

		throw new SQLException("Connection to DB failed.");
	}

	/**
	 * If an opened connection to the DB is not available, tries to connect to the DB and returns the connection.
	 * @return The connection to the DB.
	 */
	public static Connection getConnection() throws SQLException {
		if (conn == null || conn.isClosed())
			connect();
		return conn;
	}

/** Utility method, useful to close the resources associated to a DB transaction.
 * @param stmt The statement.
 * @param rs The result set.
 */
	public static void closeResources (Statement stmt, ResultSet rs) {
		try {
			if (rs!= null)
				rs.close();
			if (stmt!= null)
				stmt.close();
		} catch (SQLException e) {
			System.err.println("DB_MANAGER: Error while closing resources.");
		}
	}

	public static void closeConnection () {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				System.err.println("DB_MANAGER: Error while closing connection:\n"+e);
			}
		}
		conn = null;
	}

}
